﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace IdentityModelServer
{
    public class JwtHelper
    {
        public static string IssueJwt(TokenModelJwt model)
        {

            var iss = "copapi";


            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub ,"aos"),
                new Claim(JwtRegisteredClaimNames.Iat ,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf ,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Exp ,$"{new DateTimeOffset(DateTime.Now.AddHours(1)).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Iss ,"copapi"),
                new Claim(JwtRegisteredClaimNames.Aud ,"aos"),
            };

            claims.Add(new Claim(ClaimTypes.Role, "test-role-1"));
            claims.Add(new Claim(ClaimTypes.Role, "test-role-2"));
            claims.Add(new Claim(ClaimTypes.Role, "test-role-3"));

            var jwt = new JwtSecurityToken(
                issuer: iss,
                claims: claims
            );

            var jwtHandler = new JwtSecurityTokenHandler();
            var encodedJwt = jwtHandler.WriteToken(jwt);

            return encodedJwt;
        }
    }

    public class TokenModelJwt
    {
        /// <summary>
        /// Id
        /// </summary>
        public long Uid { get; set; }
        /// <summary>
        /// 角色
        /// </summary>
        public string Role { get; set; }
        /// <summary>
        /// 职能
        /// </summary>
        public string Work { get; set; }

    }
}
